package bean

import (
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"fmt"
	"time"
	"encoding/json"
	"github.com/hyperledger/fabric/protos/peer"
)




type Regulator struct {
	Timestamp         int64  `json:"timestamp"`           //本条记录创建时间戳
	Uid               string `json:"uid"`                 //商品唯一ID（32位MD5）
	Source       	  string `json:"source"`			    //来源
	Whereabouts       string`json:"whereabouts"`		    //去向
	ProductParameters string`json:"productParameters"`	//产品参数
}
//args 参数 name 组织名



func CreateRegulator(stub shim.ChaincodeStubInterface,args []string,name string)error{
	if len(args)!=4{
		return fmt.Errorf("Paremeter count error while Loan,count must 5")
	}

	var regulator Regulator
	regulator.Uid=args[0]
	regulator.Source=args[1]
	regulator.Whereabouts=args[2]
	regulator.ProductParameters=args[3]
	regulator.Timestamp=time.Now().Unix()
	compactJsonBytes,err:=json.Marshal(&regulator)
	if err!=nil{
		return fmt.Errorf("Json serialize Compact fail while Loan,compact id ="+args[0])
	}
	//生产联合主键
	key,err:=stub.CreateCompositeKey("Food",[]string{name,args[0]})
	if err!=nil{
		return fmt.Errorf("Faild to CreateCompositeKey while Loan" )
	}
	Avalbytes, err := stub.GetState(key)
	if err!=nil{
		return fmt.Errorf(string(Avalbytes))
	}
	//保存
	err=stub.PutState(key,compactJsonBytes)
	if err!=nil{
		return fmt.Errorf("Fail to PutState while Create,compact id ="+args[0])
	}
	return nil
}
func QueryRegulator(stub shim.ChaincodeStubInterface,args []string)peer.Response{
	var name string
	name="org4"
	key,err:=stub.CreateCompositeKey("Food",[]string{name,args[0]})
	if err!=nil{
		return shim.Error("Faild to CreateCompositeKey while Search" )
	}
	// Get the state from the ledger
	Avalbytes, err := stub.GetState(key)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + key + "\"}"
		return shim.Error(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + key + "\"}"
		return shim.Error(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + key + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return shim.Success(Avalbytes)
}